package com.grf.es.transport;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;

import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

public class Index {
	
	public void insert() throws UnknownHostException {
		String json = "{"+
			"\"id\":\"1\","+
			"\"title\":\"基于lucence服务器\","+
			"\"content\":\"分布式\""+"}";
		TransportClient client = getClient();
		IndexResponse response = client.
				prepareIndex("blog3","article","1").setSource(json).execute().actionGet();
		System.out.println(response.getIndex());
		System.out.println(response.getType());
		System.out.println(response.getResult());
		client.close();
	}
	
	/**
	 * 插入数据,数据源来自HashMap
	 * @throws UnknownHostException
	 */
	public void hashMap() throws UnknownHostException {
		HashMap<String, Object> map = new HashMap();
		map.put("id", "2");
		map.put("title", "666");
		map.put("content", "play");
		TransportClient client = getClient();
		client.prepareIndex("blog3","article","2").setSource(map).execute().actionGet();
		client.close();
	}
	
	/**
	 * 创建索引
	 * @throws UnknownHostException
	 */
	public void createIndex() throws UnknownHostException {
		
		TransportClient client = getClient();
		client.admin().indices().prepareCreate("blog3").get();
		client.close();
	}
	
	/**
	 * 获取客户端
	 * @return
	 * @throws UnknownHostException
	 */
	public TransportClient getClient() throws UnknownHostException {
		TransportClient client;
		Settings settings = Settings.builder().put("cluster.name","my-application").put("client.transport.sniff", false).build();
    	client = new PreBuiltTransportClient(settings);
    	client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hadoop101"),9300));
    	//System.out.println(client.toString());
    	return client;	
	}

	public void deleteIndex() {
		
	}
	
	public static void main(String[] args) throws UnknownHostException {
		Index index = new Index();
		//index.createIndex();
		//index.insert();
		index.hashMap();
	}
	
}
